import os
import traceback
import logging

from flask import request, jsonify, current_app
from loguru import logger
from werkzeug.exceptions import HTTPException


from common import ApiResponse


from flask_pydantic.exceptions import ValidationError

LOGGER = logging.getLogger(__name__)


def register_excep(app):
    @app.errorhandler(ValidationError)
    def pydantic_valid_exception(error):
        body_params = error.body_params
        form_params = error.form_params
        path_params = error.path_params
        query_params = error.query_params
        msg = {}
        if body_params is not None:
            msg["body_params"] = [
                {k: v for k, v in params.items() if k != "url"}
                for params in body_params
            ]
        if form_params is not None:
            msg["form_params"] = [
                {k: v for k, v in params.items() if k != "url"}
                for params in form_params
            ]
        if path_params is not None:
            msg["path_params"] = [
                {k: v for k, v in params.items() if k != "url"}
                for params in path_params
            ]
        if query_params is not None:
            msg["query_params"] = [
                {k: v for k, v in params.items() if k != "url"}
                for params in query_params
            ]
        LOGGER.exception(error)
        traceback.print_exc()
        return ApiResponse().error("请求参数不符合要求").set_data(msg).json(), 400
